package com.cug.smartranch.animal.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUnit;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.cug.smartranch.animal.admin.common.enums.DeleteEnum;
import com.cug.smartranch.animal.admin.common.enums.HealthStatusEnum;
import com.cug.smartranch.animal.admin.dao.entity.Animal;
import com.cug.smartranch.animal.admin.dao.entity.AnimalHealth;
import com.cug.smartranch.animal.admin.dao.mapper.AnimalHealthMapper;
import com.cug.smartranch.animal.admin.dao.mapper.AnimalMapper;
import com.cug.smartranch.animal.admin.dto.req.AnimalHealthSaveReqDTO;
import com.cug.smartranch.animal.admin.dto.resp.AnimalHealthQueryRespDTO;
import com.cug.smartranch.animal.admin.service.AnimalHealthService;
import com.cug.smartranch.animal.admin.service.AnimalService;
import com.cug.smartranch.framework.exception.ClientException;
import com.cug.smartranch.framework.exception.ServiceException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.BatchResult;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 动物坐标业务逻辑实现层
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class AnimalHealthServiceImpl extends ServiceImpl<AnimalHealthMapper, AnimalHealth> implements AnimalHealthService {

    private final AnimalHealthMapper animalHealthMapper;
    private final AnimalMapper animalMapper;
    private final AnimalService animalService;

    /**
     * 创建该动物当前的健康记录
     * @param requestParam 请求参数
     */
    @Override
    public void createAnimalHealth(AnimalHealthSaveReqDTO requestParam) {
        log.info("AnimalHealthServiceImpl createAnimalHealth方法入参：{}",requestParam);
        //参数判空校验
        if(requestParam.getAnimalId()==null){
            throw new ClientException("动物id为空");
        }
        if(requestParam.getTemperature()==null){
            throw new ClientException("动物体温为空");
        }
        if(requestParam.getHeartRate()==null){
            throw new ClientException("动物心率为空");
        }
        if(requestParam.getRespirationRate()==null){
            throw new ClientException("动物呼吸频率为空");
        }
        if(requestParam.getBloodGlucose()==null){
            throw new ClientException("动物血压为空");
        }
        if(requestParam.getBodyWeight()==null){
            throw new ClientException("动物体重为空");
        }
        //校验动物是否被删除
        animalService.checkAnimalDelete(requestParam.getAnimalId());

        AnimalHealth animalHealth = BeanUtil.toBean(requestParam, AnimalHealth.class);

        //健康评分初始化
        // 评分初始化
        Integer temperatureScore = getTemperatureScore(requestParam.getTemperature());
        Integer heartRateScore = getHeartRateScore(requestParam.getHeartRate());
        Integer respirationRateScore = getRespirationRateScore(requestParam.getRespirationRate());
        Integer bloodGlucoseScore = getBloodGlucoseScore(requestParam.getBloodGlucose());
        Integer bodyWeightScore = getBodyWeightScore(requestParam.getBodyWeight());

        // 计算综合得分
        Integer totalScore = temperatureScore + heartRateScore + respirationRateScore + bloodGlucoseScore + bodyWeightScore;

        // 根据得分判断健康状态
        if (totalScore >= 4) {
            animalHealth.setHealthStatus(HealthStatusEnum.HEALTHY.getType());
        } else if (totalScore >= 2) {
            animalHealth.setHealthStatus(HealthStatusEnum.SUBHEALTHY.getType());
        } else if (totalScore >= 0) {
            animalHealth.setHealthStatus(HealthStatusEnum.UNHEALTHY.getType());
        } else {
            animalHealth.setHealthStatus(HealthStatusEnum.DEATH.getType());
        }

        //插入健康记录
        int insert = animalHealthMapper.insert(animalHealth);
        if(insert>0){
            return;
        }else{
            throw new ServiceException("动物健康记录新增异常");
        }
    }

    /**
     * 查询某个动物近期100条健康状态记录
     * @param animalId
     * @return 某个动物近期100条健康状态记录
     */
    @Override
    public List<AnimalHealthQueryRespDTO> findAnimalHealth(Long animalId) {
        log.info("AnimalHealthServiceImpl findAnimalHealth：{}", animalId);
        if (animalId == null) {
            throw new ClientException("动物id为空");
        }
        //校验该动物是否被删除
        animalService.checkAnimalDelete(animalId);
        //构建查询参数
        LambdaQueryWrapper<AnimalHealth> queryWrapper = Wrappers.lambdaQuery(AnimalHealth.class);
        queryWrapper.eq(AnimalHealth::getAnimalId, animalId);
        queryWrapper.eq(AnimalHealth::getDelFlag, DeleteEnum.NORMAL.getType());
        queryWrapper.orderByDesc(AnimalHealth::getCreateTime);
        Page<AnimalHealth> page = new Page<>(1, 100);
        //分页查询
        List<AnimalHealth> list = animalHealthMapper.selectPage(page, queryWrapper).getRecords();
        //封装响应体
        List<AnimalHealthQueryRespDTO> resultList = list.stream().map(animalHealth -> {
            AnimalHealthQueryRespDTO respDTO = BeanUtil.toBean(animalHealth, AnimalHealthQueryRespDTO.class);
            return respDTO;
        }).collect(Collectors.toList());
        return resultList;
    }

    /**
     * 创建测试数据
     * @param animalId
     */
    @Override
    public void createMockAnimalHealth(Long animalId) {
        //校验该动物是否被删除
        animalService.checkAnimalDelete(animalId);
        //校验该动物的健康记录是否超过100条，如果超过就无需创建
        LambdaQueryWrapper<AnimalHealth> queryWrapper = Wrappers.lambdaQuery(AnimalHealth.class);
        queryWrapper.eq(AnimalHealth::getAnimalId, animalId);
        queryWrapper.eq(AnimalHealth::getDelFlag, DeleteEnum.NORMAL.getType());
        List<AnimalHealth> list = animalHealthMapper.selectList(queryWrapper);
        if (list.size() > 100) {
            throw new ClientException("动物健康测试记录已经够多了，不用创建了~~~");
        }
        // 随机数生成器
        Random rand = new Random();
        // 存储动物对象的列表
        List<AnimalHealth> animalHealths = new ArrayList<>();
        int x=1;
        // 创建100个动物健康记录
        while(true){
            // 随机生成各项健康数据
            Integer temperature = rand.nextInt(50) + 30; // 30到80之间的体温
            Integer heartRate = rand.nextInt(120) + 30;   // 30到150之间的心率
            Integer respirationRate = rand.nextInt(50) + 5; // 5到55之间的呼吸频率
            Double bloodGlucose = 40 + rand.nextDouble() * 200; // 40到240之间的血糖值
            Double bodyWeight = 10.0 + rand.nextDouble() * 50.0; // 10到60之间的体重值

            // 创建AnimalHealth对象
            AnimalHealth build = AnimalHealth.builder()
                    .animalId(animalId)
                    .temperature(temperature)
                    .heartRate(heartRate)
                    .respirationRate(respirationRate)
                    .bloodGlucose(bloodGlucose)
                    .bodyWeight(bodyWeight)
                    .build();
            Integer temperatureScore = getTemperatureScore(build.getTemperature());
            Integer heartRateScore = getHeartRateScore(build.getHeartRate());
            Integer respirationRateScore = getRespirationRateScore(build.getRespirationRate());
            Integer bloodGlucoseScore = getBloodGlucoseScore(build.getBloodGlucose());
            Integer bodyWeightScore = getBodyWeightScore(build.getBodyWeight());
            Integer totalScore = temperatureScore + heartRateScore + respirationRateScore + bloodGlucoseScore + bodyWeightScore;
            // 根据得分判断健康状态
            if (totalScore >= 4) {
                build.setHealthStatus(HealthStatusEnum.HEALTHY.getType());
            } else if (totalScore >= 2) {
                build.setHealthStatus(HealthStatusEnum.SUBHEALTHY.getType());
            } else if (totalScore >= 0) {
                build.setHealthStatus(HealthStatusEnum.UNHEALTHY.getType());
            } else {
                continue;
            }
            // 获取当前日期
            Date currentDate = new Date();
            // 使用 Calendar 类
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(currentDate);
            // 将日期回退x天
            calendar.add(Calendar.DAY_OF_YEAR, -x);
            // 获取前x天的 Date 对象
            Date previousDate = calendar.getTime();
            build.setCreateTime(previousDate);
            build.setUpdateTime(previousDate);
            x++;
            System.out.println(x);
            // 将Animal对象加入列表
            animalHealths.add(build);
            if(animalHealths.size()==100){
                break;
            }
        }
        boolean flag = saveBatch(animalHealths);
        if(!flag){
            throw new ClientException("创建测试数据失败，请查看数据库数据是否有异常");
        }
    }

    /**
     * 查看牲畜健康情况（饼状图）
     * @return
     */
    @Override
    public Map<String, Double> findAnimalHealthRatio() {
        // 获得健康统计map（次数），key为HealthStatusEnum枚举值，value为对应枚举出现的次数
        Map<Integer, Integer> originalMap = new HashMap<>();
        List<Long> ids = animalService.selectAllAnimalIds();
        for (Long id : ids) {
            LambdaQueryWrapper<AnimalHealth> queryWrapper = Wrappers.lambdaQuery(AnimalHealth.class);
            queryWrapper.eq(AnimalHealth::getAnimalId, id);
            queryWrapper.orderByDesc(AnimalHealth::getCreateTime); // 按 create_time 降序排序
            queryWrapper.last("LIMIT 1");
            List<AnimalHealth> list = animalHealthMapper.selectList(queryWrapper);
            if (!CollectionUtil.isEmpty(list)) {
                AnimalHealth animalHealth = list.get(0);
                Integer healthStatus = animalHealth.getHealthStatus();
                originalMap.put(healthStatus, originalMap.getOrDefault(healthStatus, 0) + 1);
            }
        }

        // 获得健康统计map(百分比),key为HealthStatusEnum枚举值，value为对应枚举的百分占比
        // 计算总数
        int totalCount = originalMap.values().stream().mapToInt(Integer::intValue).sum();
        // 创建一个新的 Map 用于存储百分比
        Map<Integer, Double> percentageMap = new HashMap<>();
        // 遍历原始 Map，计算每个枚举的百分比占比
        for (Map.Entry<Integer, Integer> entry : originalMap.entrySet()) {
            int enumValue = entry.getKey();
            int count = entry.getValue();
            // 计算百分占比
            double percentage = (double) count / totalCount * 100;
            // 存入新的 Map，value 是百分比占比
            percentageMap.put(enumValue, percentage);
        }

        // key枚举由数字转换为字符串
        Map<String,Double> result = new HashMap<>();
        for(Map.Entry<Integer, Double> entry : percentageMap.entrySet()){
            Integer enumValue = entry.getKey();
            Double percent = entry.getValue();
            String type = HealthStatusEnum.findValueByType(enumValue);
            result.put(type, percent);
        }
        return result;
    }

    // 体温评分
    private static Integer getTemperatureScore(Integer temperature) {
        if (temperature >= 36 && temperature <= 39) {
            return 1; // 正常
        } else if (temperature > 35 && temperature < 37 || temperature > 39 && temperature < 42) {
            return 0; // 异常
        } else {
            return -1; // 严重异常
        }
    }

    // 心率评分
    private static Integer getHeartRateScore(Integer heartRate) {
        if (heartRate >= 60 && heartRate <= 120) {
            return 1; // 正常
        } else if (heartRate > 30 && heartRate < 60 || heartRate > 120 && heartRate < 150) {
            return 0; // 异常
        } else {
            return -1; // 严重异常
        }
    }

    // 呼吸频率评分
    private static Integer getRespirationRateScore(Integer respirationRate) {
        if (respirationRate >= 12 && respirationRate <= 30) {
            return 1; // 正常
        } else if (respirationRate > 7 && respirationRate < 12 || respirationRate > 30 && respirationRate < 45) {
            return 0; // 异常
        } else {
            return -1; // 严重异常
        }
    }

    // 血糖评分
    private static Integer getBloodGlucoseScore(Double bloodGlucose) {
        if (bloodGlucose >= 70 && bloodGlucose <= 150) {
            return 1; // 正常
        } else if (bloodGlucose > 40 && bloodGlucose < 70 || bloodGlucose > 150 && bloodGlucose < 180) {
            return 0; // 异常
        } else {
            return -1; // 严重异常
        }
    }

    // 体重评分（可以根据物种进行具体范围设定，这里假设体重值在正常范围内）
    private static Integer getBodyWeightScore(Double bodyWeight) {
        if (bodyWeight >= 15.0 && bodyWeight <= 20.0) {  // 假设范围
            return 1; // 正常
        } else {
            return 0; // 异常
        }
    }

    /*public static void main(String[] args) {
        // 随机数生成器
        Random rand = new Random();

        // 存储动物对象的列表
        List<AnimalHealth> animalHealths = new ArrayList<>();

        int x=1;
        // 创建100个动物健康记录
        while(true){
            // 随机生成各项健康数据
            Integer temperature = rand.nextInt(50) + 30; // 30到80之间的体温
            Integer heartRate = rand.nextInt(120) + 30;   // 30到150之间的心率
            Integer respirationRate = rand.nextInt(50) + 5; // 5到55之间的呼吸频率
            Double bloodGlucose = 40 + rand.nextDouble() * 200; // 40到240之间的血糖值
            Double bodyWeight = 10.0 + rand.nextDouble() * 50.0; // 10到60之间的体重值

            // 创建AnimalHealth对象
            AnimalHealth build = AnimalHealth.builder()
                    .animalId(1L)
                    .temperature(temperature)
                    .heartRate(heartRate)
                    .respirationRate(respirationRate)
                    .bloodGlucose(bloodGlucose)
                    .bodyWeight(bodyWeight)
                    .build();
            Integer temperatureScore = getTemperatureScore(build.getTemperature());
            Integer heartRateScore = getHeartRateScore(build.getHeartRate());
            Integer respirationRateScore = getRespirationRateScore(build.getRespirationRate());
            Integer bloodGlucoseScore = getBloodGlucoseScore(build.getBloodGlucose());
            Integer bodyWeightScore = getBodyWeightScore(build.getBodyWeight());
            Integer totalScore = temperatureScore + heartRateScore + respirationRateScore + bloodGlucoseScore + bodyWeightScore;
            // 根据得分判断健康状态
            if (totalScore >= 4) {
                build.setHealthStatus(HealthStatusEnum.HEALTHY.getType());
            } else if (totalScore >= 2) {
                build.setHealthStatus(HealthStatusEnum.SUBHEALTHY.getType());
            } else if (totalScore >= 0) {
                build.setHealthStatus(HealthStatusEnum.UNHEALTHY.getType());
            } else {
                continue;
            }
            // 获取当前日期
            Date currentDate = new Date();
            // 使用 Calendar 类
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(currentDate);
            // 将日期回退x天
            calendar.add(Calendar.DAY_OF_YEAR, -x);
            // 获取前x天的 Date 对象
            Date previousDate = calendar.getTime();
            build.setCreateTime(previousDate);
            build.setUpdateTime(previousDate);
            x++;
            System.out.println(x);
            // 将Animal对象加入列表
            animalHealths.add(build);
            if(animalHealths.size()==100){
                break;
            }
        }

        // 打印前100个动物的健康数据
        for (int i = 0; i < 100; i++) {
            AnimalHealth animalHealth = animalHealths.get(i);
            //健康评分初始化
            // 评分初始化
            Integer temperatureScore = getTemperatureScore(animalHealth.getTemperature());
            Integer heartRateScore = getHeartRateScore(animalHealth.getHeartRate());
            Integer respirationRateScore = getRespirationRateScore(animalHealth.getRespirationRate());
            Integer bloodGlucoseScore = getBloodGlucoseScore(animalHealth.getBloodGlucose());
            Integer bodyWeightScore = getBodyWeightScore(animalHealth.getBodyWeight());

            // 计算综合得分
            Integer totalScore = temperatureScore + heartRateScore + respirationRateScore + bloodGlucoseScore + bodyWeightScore;

            // 根据得分判断健康状态
            if (totalScore >= 4) {
                animalHealth.setHealthStatus(HealthStatusEnum.HEALTHY.getType());
                System.out.println(animalHealth.getAnimalId()+"动物:"+"健康");
                // 创建一个SimpleDateFormat对象，指定输出格式
                System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(animalHealth.getCreateTime()));
            } else if (totalScore >= 2) {
                animalHealth.setHealthStatus(HealthStatusEnum.SUBHEALTHY.getType());
                System.out.println(animalHealth.getAnimalId()+"动物:"+"亚健康");
                System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(animalHealth.getCreateTime()));
            } else if (totalScore >= 0) {
                animalHealth.setHealthStatus(HealthStatusEnum.UNHEALTHY.getType());
                System.out.println(animalHealth.getAnimalId()+"动物:"+"不健康");
                System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(animalHealth.getCreateTime()));
            } else {
                animalHealth.setHealthStatus(HealthStatusEnum.DEATH.getType());
                System.out.println(animalHealth.getAnimalId()+"动物:"+"死亡");
                System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(animalHealth.getCreateTime()));
            }
        }
    }*/
}
